package com.hui.qiniucloud.controller;

import com.hui.qiniucloud.entity.AICharacter;
import com.hui.qiniucloud.entity.AppHttpCodeEnum;
import com.hui.qiniucloud.entity.Result;
import com.hui.qiniucloud.entity.User;
import com.hui.qiniucloud.service.ICharacterService;
import com.hui.qiniucloud.service.IDoubaoUniversalService;
import com.hui.qiniucloud.dto.ImageGenerateRequest;
import com.hui.qiniucloud.dto.ImageGenerateResponse;
import com.hui.qiniucloud.utils.AppThreadLocalUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * <p>
 * AI角色表 前端控制器
 * </p>
 *
 * @author huihui
 * @since 2025-09-28
 */
@Slf4j
@RestController
@RequestMapping("/api/character")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
@Tag(name = "AI角色管理", description = "AI角色相关接口，支持用户自定义角色")
public class CharacterController {

    private final ICharacterService characterService;
    private final IDoubaoUniversalService doubaoUniversalService;

    /**
     * 获取系统预设角色
     */
    @GetMapping("/system")
    @Operation(summary = "获取系统预设角色", description = "获取所有系统预设的AI角色")
    public Result<List<AICharacter>> getSystemCharacters() {
        try {
            List<AICharacter> characters = characterService.getSystemCharacters();
            return Result.success(characters);
        } catch (Exception e) {
            log.error("获取系统角色失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 获取用户角色列表
     */
    @GetMapping("/user")
    @Operation(summary = "获取用户角色", description = "获取指定用户创建的所有角色")
    public Result<List<AICharacter>> getUserCharacters() {
        //获取当前用户id
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Long userId = user.getId();
        try {
            List<AICharacter> characters = characterService.getUserCharacters(userId);
            return Result.success(characters);
        } catch (Exception e) {
            log.error("获取用户角色失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 搜索用户角色
     */
    @GetMapping("/user/{userId}/search")
    @Operation(summary = "搜索用户角色", description = "根据关键词搜索用户创建的角色")
    public Result<List<AICharacter>> searchUserCharacters(
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword) {
        //获取当前用户id
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Long userId = user.getId();
        try {
            List<AICharacter> characters = characterService.searchUserCharacters(userId, keyword);
            return Result.success(characters);
        } catch (Exception e) {
            log.error("搜索用户角色失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 创建用户角色
     */
    @PostMapping("/user/{userId}")
    @Operation(summary = "创建用户角色", description = "用户创建自定义AI角色")
    public Result<AICharacter> createUserCharacter(
            @Valid @RequestBody AICharacter aiCharacter) {
        //获取当前用户id
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Long userId = user.getId();
        try {
            return characterService.createUserCharacter(aiCharacter, userId);
        } catch (Exception e) {
            log.error("创建用户角色失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 更新用户角色
     */
    @PutMapping("/update")
    @Operation(summary = "更新用户角色", description = "用户更新自己创建的角色")
    public Result<AICharacter> updateUserCharacter(
            @Valid @RequestBody AICharacter aiCharacter) {
        //获取当前用户id
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Long userId = user.getId();
        try {
            return characterService.updateUserCharacter(aiCharacter, userId);
        } catch (Exception e) {
            log.error("更新用户角色失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 删除用户角色
     */
    @DeleteMapping("/user/{characterId}")
    @Operation(summary = "删除用户角色", description = "用户删除自己创建的角色")
    public Result<String> deleteUserCharacter(
            @Parameter(description = "角色ID") @PathVariable String characterId) {
        //获取当前用户id
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Long userId = user.getId();
        try {
            return characterService.deleteUserCharacter(characterId, userId);
        } catch (Exception e) {
            log.error("删除用户角色失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 获取角色详情
     */
    @GetMapping("/{characterId}")
    @Operation(summary = "获取角色详情", description = "根据角色ID获取角色详细信息")
    public Result<AICharacter> getCharacterById(@Parameter(description = "角色ID") @PathVariable String characterId) {
        try {
            AICharacter character = characterService.getCharacterById(characterId);
            if (character == null) {
                return Result.fail("角色不存在");
            }
            return Result.success(character);
        } catch (Exception e) {
            log.error("获取角色详情失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 获取所有角色（系统+用户）
     */
    @GetMapping("/all")
    @Operation(summary = "获取所有角色", description = "获取系统预设角色和所有用户角色")
    public Result<List<AICharacter>> getAllCharacters() {
        try {
            List<AICharacter> characters = characterService.getAllCharacters();
            return Result.success(characters);
        } catch (Exception e) {
            log.error("获取所有角色失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 搜索所有角色
     */
    @GetMapping("/search")
    @Operation(summary = "搜索角色", description = "根据关键词搜索所有角色")
    public Result<List<AICharacter>> searchCharacters(@Parameter(description = "搜索关键词") @RequestParam String keyword) {
        try {
            List<AICharacter> characters = characterService.searchCharacters(keyword);
            return Result.success(characters);
        } catch (Exception e) {
            log.error("搜索角色失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 文生图接口
     */
    @PostMapping("/generate-image")
    @Operation(summary = "文生图",
               description = "根据文本描述生成图像",
               requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                   description = "文生图请求参数",
                   content = @io.swagger.v3.oas.annotations.media.Content(
                       mediaType = "application/json",
                       examples = @io.swagger.v3.oas.annotations.media.ExampleObject(
                           name = "文生图示例",
                           summary = "文生图请求示例",
                           value = """
                               {
                                 "prompt": "鱼眼镜头，一只猫咪的头部，画面呈现出猫咪的五官因为拍摄方式扭曲的效果。",
                                 "size": "1024x1024",
                                 "seed": 12,
                                 "guidanceScale": 2.5,
                                 "watermark": true,
                                 "responseFormat": "url"
                               }
                               """
                       )
                   )
               ))
    @io.swagger.v3.oas.annotations.responses.ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "图像生成成功",
                content = @io.swagger.v3.oas.annotations.media.Content(
                    mediaType = "application/json",
                    examples = @io.swagger.v3.oas.annotations.media.ExampleObject(
                        name = "文生图响应示例",
                        value = """
                            {
                              "success": true,
                              "data": {
                                "model": "doubao-seedream-3-0-t2i-250415",
                                "created": 1589478378,
                                "data": [
                                  {
                                    "url": "https://example.com/generated-image.jpg"
                                  }
                                ],
                                "usage": {
                                  "generatedImages": 1,
                                  "outputTokens": 100,
                                  "totalTokens": 150
                                }
                              }
                            }
                            """
                    )
                )),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未登录"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "服务器错误")
    })
    public Result<ImageGenerateResponse> generateImage(@Valid @RequestBody ImageGenerateRequest request) {
//        User user = AppThreadLocalUtil.getUser();
//        if (user == null) {
//            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
//        }

        try {
            ImageGenerateResponse response = doubaoUniversalService.generateImage(request).block();
//            log.info("用户 {} 成功生成图像，提示词: {}", user.getUsername(), request.getPrompt());
            return Result.success(response);
        } catch (Exception e) {
            log.error("文生图失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    // 保留原有的管理员接口（兼容性）
    @PostMapping("/create")
    @Operation(summary = "创建角色（管理员）", description = "管理员创建系统角色")
    public Result<AICharacter> create(@Valid @RequestBody AICharacter aiCharacter) {
        try {
            return characterService.create(aiCharacter);
        } catch (Exception e) {
            log.error("创建角色失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    @PostMapping("/update")
    @Operation(summary = "更新角色（管理员）", description = "管理员更新角色")
    public Result<AICharacter> update(@Valid @RequestBody AICharacter aiCharacter) {
        try {
            return characterService.update(aiCharacter);
        } catch (Exception e) {
            log.error("更新角色失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    @PostMapping("/delete")
    @Operation(summary = "删除角色（管理员）", description = "管理员删除角色")
    public Result<String> delete(@Parameter(description = "角色ID") @RequestParam("id") String id) {
        try {
            return characterService.delete(id);
        } catch (Exception e) {
            log.error("删除角色失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }
}
